import { createStore } from 'vuex'
import {COZE_ACCESS_TOKEN, COZE_EXPIRES_IN} from "@/utils/constant";
import {userAPI} from "@/utils/api";
const store = createStore({
	state:{//存放状态
		cozeAccessToken: uni.getStorageSync(COZE_ACCESS_TOKEN) || '',
		cozeExpiresIn: uni.getStorageSync(COZE_EXPIRES_IN) || null,
	},

	mutations:{
		SET_COZE_ACCESS_TOKEN(state, token) {
			state.cozeAccessToken = token
			uni.setStorageSync(COZE_ACCESS_TOKEN, token)
		},

		SET_COZE_EXPIRES_IN(state, expires_in) {
			state.cozeExpiresIn = expires_in
			uni.setStorageSync(COZE_EXPIRES_IN, expires_in)
		}
	},

	actions:{
		async setCozeAccessToken({ commit, state }, clientId) {
			if (state.cozeAccessToken && state.cozeExpiresIn > Math.floor(Date.now() / 1000)) {
				return state.cozeAccessToken
			}
			const res = await userAPI.getCozeAccessToken({ clientId })
			const expires_in  = res.expires_in
			const token = res.access_token

			commit('SET_COZE_ACCESS_TOKEN', token)
			commit('SET_COZE_EXPIRES_IN', expires_in)
		}
	},
	getters: {
		getCozeAccessToken: state => state.cozeAccessToken,
		getCozeExpiresIn: state => state.cozeExpiresIn
	}
})

export default store